//
//  PhotoViewerController.swift
//  DXWeibo
//
//  Created by dx on 17/2/22.
//  Copyright © 2017年 dx. All rights reserved.
//

import UIKit

/// 单张照片查看控制器
class PhotoViewerController: UIViewController {

    // MARK: - 属性和控件
    fileprivate lazy var scrollView = UIScrollView()
    fileprivate lazy var imageView = UIImageView()
    
    private let urlString: String
    let photoIndex: Int
    
    // MARK: - 构造函数
    init(urlString: String, photoIndex: Int) {
        self.urlString = urlString
        self.photoIndex = photoIndex
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadImage()
    }
    
    /// 加载图像
    private func loadImage() {
        guard let url = URL(string: urlString) else {
            return
        }
        imageView.sd_setImage(with: url) { (image, _, _, _) in
            guard let image = image else {
                return
            }
            
            self.setImagePosition(image: image)

        }
    }
    
    private func setImagePosition(image: UIImage) {
        let size = imageSizeWithScreen(image: image)
        imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        // 长图需要滚动
        scrollView.contentSize = size
        // 短图置中
        if size.height < scrollView.bounds.height {
            imageView.frame.origin.y = (scrollView.bounds.height - size.height) * 0.5
        }
    }
    
    private func imageSizeWithScreen(image: UIImage) -> CGSize {
        var size = UIScreen.main.bounds.size
        size.height = image.size.height * size.width / image.size.width
        return size
    }
}

// MARK: - 设置界面
extension PhotoViewerController {
    
    fileprivate func setupUI() {
        view.backgroundColor = UIColor.green
        
        view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        scrollView.frame = view.bounds
    }
}
